Dashboard Temp Share Shortlinks Frames API

HTMLify

Binary search.cpp
Views: 1 | Author: cody
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n = nums.size();
        int start = 0;
        int end = n - 1;
        
        
        while(start<=end){
            int mid = start + (end - start)/2;
            if(nums[mid]== target){
                return mid;
            }
            else if(target > nums[mid]){
                start = mid + 1;
            }
            else{
                end = mid - 1;
            }
            
        }
        return -1;
    }
};